import { useMount } from 'ahooks'
import { useState, useCallback } from 'react'
import { Menu, Tooltip, Button, App } from 'antd'
import { MenuFoldOutlined, MenuUnfoldOutlined, } from '@ant-design/icons'

import { consoleStyle } from '../../Config/theme'
import { ICONMapping } from '../../Config/IconMapping'

import { themeStore, pageStore } from '../../Config/zustand'
import { GetIndexedDB, PutIndexedDB } from '../../Utils/IndexedDB'
import { treeValue, objectArrHas, ColorCallBack } from '../../Utils'

const MenuTemplate = () => {
    const { notification } = App.useApp();
    const { menu, theme, updateMenu, body } = themeStore()
    const { pageActive, updateActive, pageList, updateList } = pageStore()
    const { tabsMax } = body

    const { isFold, menuBack, menuPx, menuRadio, menuShadow, menuMargin, menuMax } = menu
    const { fontColor, fontFamily, fontWeight, fontStyle, fontSize, fontShadowX, fontShadowY, fontShadowS, fontShadowB } = menu
    const { iconColor, iconSize, iconIndex, iconShadowX, iconShadowY, iconShadowS, iconShadowB } = menu

    const menuStyle = {
        '--theme': theme.color,
        '--theme2': theme.color + 33,
        borderRadius: menuRadio,
        '--fontColor': fontColor,
        '--fontFamily': fontFamily,
        '--fontWeight': fontWeight,
        '--fontStyle': fontStyle,
        '--fontSize': fontSize + 'px',
        '--fontShadowX': fontShadowX + 'px',
        '--fontShadowY': fontShadowY + 'px',
        '--fontShadowS': fontShadowS + 'px',
        '--fontShadowB': fontShadowB,
        '--iconColor': iconColor,
        '--iconSize': iconSize + 'px',
        '--iconIndex': iconIndex + 'px',
        '--iconShadowX': iconShadowX + 'px',
        '--iconShadowY': iconShadowY + 'px',
        '--iconShadowS': iconShadowS + 'px',
        '--iconShadowB': iconShadowB,
    }

    const menuBoxStyle = {
        background: ColorCallBack(menuBack),
        borderRadius: menuRadio,
        backdropFilter: `blur(${menuPx}px)`,
        margin: menuMargin,
        boxShadow: `var(${menuShadow})`,
        maxWidth: menuMax,
    }

    const [MenuArr, setMenuArr] = useState([])
    const [MenuList, setMenuList] = useState([])
    const getItem = ({ uuid, isEnabled, other, mapping }) => {
        const { tableName, targetUrl, icon } = other
        return { key: uuid, label: mapping[uuid] || tableName, icon: icon ? ICONMapping[icon] : null, enabled: isEnabled, url: targetUrl }
    }

    const getMenu = useCallback((menu, role, state, mapping) => {
        // 角色状态的提前判断有与变量合并项
        return menu.reduce((menuData, { uuid, isEnabled, children, type, ...other }) => {
            if (isEnabled === 0 || type === 'power') return menuData
            const item = getItem({ uuid, isEnabled, other, mapping })
            if (!state) {
                if (children?.length) {
                    const childMenu = getMenu(children, role, state, mapping)
                    if (childMenu.length > 0) item.children = childMenu
                }
                menuData.push(item)
            } else if (state) {
                if (children?.length) {
                    const childMenu = getMenu(children, role, state, mapping)
                    if (childMenu.length > 0) item.children = childMenu
                }
                menuData.push(item)
            }
            return menuData
        }, [])
    }, [])
    const getDBMenu = async () => {
        const menu = await GetIndexedDB('menu')
        const data = getMenu(menu[0].children, {}, '', {})
        setMenuArr(menu)
        setMenuList(data)
    }
    useMount(getDBMenu)

    const onIsFold = () => {
        menu.isFold = !isFold
        updateMenu(menu)
    }

    const onSelect = async ({ key }) => {
        if (tabsMax !== 0 && pageList.length >= tabsMax) {
            notification.error({ key: 'system', message: '打开失败', description: `超过最大打开数量 ${tabsMax}` })
            return false
        }
        updateActive(key)
        await PutIndexedDB('openKey', key)
        const { uuid, tableName, targetUrl, icon, type } = treeValue(MenuArr, key)
        if (!objectArrHas(pageList, key, 'key')) {
            console.info(`%c[打开 ${tableName} -- ${targetUrl}]`, consoleStyle)
            updateList([...pageList, { key: uuid, label: tableName, url: targetUrl, icon, type }])
        } else {
            console.info(`%c[切换 ${tableName} -- ${targetUrl}]`, consoleStyle)
        }
    }

    return (
        <div className='MenuTemplate' style={menuBoxStyle} >
            <div className='Menu' style={menuStyle}>
                <Menu
                    mode="inline"
                    selectedKeys={[pageActive]}
                    inlineCollapsed={isFold}
                    items={MenuList}
                    onSelect={onSelect}
                />
                <div className='isFold' >
                    <Tooltip title={isFold ? '展开' : '收起'}>
                        <Button type="line" icon={isFold ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />} onClick={onIsFold} />
                    </Tooltip>
                </div>
            </div>
        </div>
    );
};

export default MenuTemplate;